package com.ruoyi.common.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.ConnectionPool;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * OkHttp工具类
 * 
 * @author lincm
 * @date 2022/12/06
 */
@Component
@Slf4j
public class OkHttpUtil {

    public static final String FILEDEFAULTPATH = "/tmp/file/";
    public static final String AIMOTIONPATH = FILEDEFAULTPATH + "aimotion/";
    public static final String AIMOTION_MP4 = AIMOTIONPATH + "mp4/";

    private static final Long TIME_OUT = 5L;
    private static final MediaType JSON_MT = MediaType.parse("application/json; charset=utf-8");
    // private static final MediaType XML_MT = MediaType.parse("application/xml;
    // charset=utf-8");
    private static OkHttpClient okHttpClient;

    public OkHttpUtil() {
        OkHttpUtil.okHttpClient = new OkHttpClient.Builder().retryOnConnectionFailure(false).connectionPool(pool())
            .connectTimeout(TIME_OUT, TimeUnit.MINUTES).readTimeout(TIME_OUT, TimeUnit.MINUTES)
            .callTimeout(TIME_OUT, TimeUnit.MINUTES).writeTimeout(TIME_OUT, TimeUnit.MINUTES).build();
    }

    // ---------------------------配置--------------------------------------
    public ConnectionPool pool() {
        return new ConnectionPool(200, 5, TimeUnit.MINUTES);
    }

    // ---------------------------GET--------------------------------------

    public static String getJson(String url) throws IOException {
        return getJsonWithHeader(url, null, null);
    }

    public static String getJson(String url, Map<String, Object> param) throws IOException {
        return getJsonWithHeader(url, param, null);
    }

    public static String getJsonWithHeader(String url, Map<String, Object> params, Map<String, Object> headers)
        throws IOException {
        StringBuffer sb = new StringBuffer(url);
        if (params != null && params.keySet().size() > 0) {
            // 是否第一个参数，url是否含有[?]
            boolean firstFlag = url.indexOf("?") == -1;
            Iterator<Entry<String, Object>> iterator = params.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<String, Object> entry = iterator.next();
                if (firstFlag) {
                    sb.append("?" + entry.getKey() + "=" + entry.getValue());
                    firstFlag = false;
                } else {
                    sb.append("&" + entry.getKey() + "=" + entry.getValue());
                }
            }
        }
        Request.Builder builder = new Request.Builder().url(sb.toString());
        if (!CollectionUtils.isEmpty(headers)) {
            Set<String> set = headers.keySet();
            for (String key : set) {
                if (ObjectUtil.isNotNull(headers.get(key))) {
                    builder.addHeader(key, String.valueOf(headers.get(key)));
                }
            }
        }
        Request request = builder.build();
        long begin = System.currentTimeMillis();
        try (Response response = okHttpClient.newCall(request).execute();) {
            if (response.isSuccessful()) {
                return response.body().string();
            } else {
                log.error("第三方接口:{},头部:{},参数:{},状态码:{}", url, JSON.toJSONString(headers), JSON.toJSONString(params),
                    response.code());
                throw new IOException("第三方接口返回http状态码为" + response.code());
            }
        } catch (Exception e) {
            log.error("okhttp3 get exception：{}", e.getMessage(), e);
            throw new RuntimeException(e.getMessage());
        } finally {
            log.info("okhttp3 get {},耗时{}ms", sb.toString(), System.currentTimeMillis() - begin);
        }
    }

    public static String delJsonWithHeader(String url, Map<String, Object> headers) throws IOException {
        StringBuffer sb = new StringBuffer(url);
        Request.Builder builder = new Request.Builder().url(sb.toString());
        if (!CollectionUtils.isEmpty(headers)) {
            Set<String> set = headers.keySet();
            for (String key : set) {
                if (ObjectUtil.isNotNull(headers.get(key))) {
                    builder.addHeader(key, String.valueOf(headers.get(key)));
                }
            }
        }
        Request request = builder.delete(null).build();
        long begin = System.currentTimeMillis();
        try (Response response = okHttpClient.newCall(request).execute();) {
            if (response.isSuccessful()) {
                return response.body().string();
            } else {
                log.error("第三方接口:{},头部:{},状态码:{}", url, JSON.toJSONString(headers), response.code());
                throw new IOException("第三方接口返回http状态码为" + response.code());
            }
        } catch (Exception e) {
            log.error("okhttp3 get exception：{}", e.getMessage(), e);
            throw new RuntimeException(e.getMessage());
        } finally {
            log.info("okhttp3 get {},耗时{}ms", sb.toString(), System.currentTimeMillis() - begin);
        }
    }

    // ---------------------------POST--------------------------------------
    public static String postForm(String url, Map<String, Object> params) throws IOException {
        return postFormWithHeader(url, params, null);
    }

    public static String postFormWithHeader(String url, Map<String, Object> params, Map<String, Object> headers)
        throws IOException {
        FormBody.Builder fBuilder = new FormBody.Builder();
        // 添加参数
        if (params != null && params.keySet().size() > 0) {
            for (String key : params.keySet()) {
                if (key == "logo") {
                    String s = String.valueOf(params.get(key));
                    String[] ss = s.split(",");
                    for (String string : ss) {
                        fBuilder.add(key, string);
                    }
                } else if (ObjectUtil.isNotNull(params.get(key))) {
                    fBuilder.add(key, String.valueOf(params.get(key)));
                }
            }
        }
        Request.Builder builder = new Request.Builder().url(url).post(fBuilder.build());
        if (!CollectionUtils.isEmpty(headers)) {
            Set<String> set = headers.keySet();
            for (String key : set) {
                if (ObjectUtil.isNotNull(headers.get(key))) {
                    builder.addHeader(key, String.valueOf(headers.get(key)));
                }
            }
        }
        Request request = builder.build();
        long begin = System.currentTimeMillis();
        try (Response response = okHttpClient.newCall(request).execute();) {
            if (response.isSuccessful()) {
                return response.body().string();
            } else {
                log.error("第三方接口:{},头部:{},参数:{},状态码:{}", url, JSON.toJSONString(headers), JSON.toJSONString(params),
                    response.code());
                throw new IOException("第三方接口返回http状态码为" + response.code());
            }
        } catch (Exception e) {
            log.error("okhttp3 post exception：{}", e.getMessage(), e);
            throw new RuntimeException(e.getMessage());
        } finally {
            log.error("okhttp3 post {},耗时{}ms", url, System.currentTimeMillis() - begin);
        }
    }

    public static String postJson(String url) throws IOException {
        return postJsonWithHeader(url, "", null);
    }

    public static String postJson(String url, String json) throws IOException {
        return postJsonWithHeader(url, json, null);
    }

    public static String postJson(String url, Map<String, Object> params) throws IOException {
        return postJsonWithHeader(url, JSON.toJSONString(params), null);
    }

    public static String postJson(String url, JSONObject params) throws IOException {
        if (ObjectUtil.isNull(params)) {
            return postJsonWithHeader(url, null, null);

        } else {
            return postJsonWithHeader(url, JSON.toJSONString(params), null);

        }
    }

    public static String postJsonWithHeader(String url, String json, JSONObject headers) throws IOException {
        log.info("postJsonWithHeader.params:{}", json);
        return postWithHeader(url, json, headers, JSON_MT);
    }

    public static String postJsonDataWithHeader(String url, JSONObject params, JSONObject headers) throws IOException {
        log.info("postJsonWithHeader.url{}.params:{}", url, params);
        return postWithHeader(url, params.toJSONString(), headers, JSON_MT);
    }

    public static String postWithHeader(String url, String json, Map<String, Object> headers, MediaType mediaType)
        throws IOException {
        Request.Builder builder = null;
        if (StrUtil.isNotEmpty(json)) {
            RequestBody body = RequestBody.create(json, mediaType);
            log.info("postJsonWithHeader.body:{}", body.toString());
            builder = new Request.Builder().url(url).post(body);
        } else {
            builder = new Request.Builder().url(url);
        }

        if (!CollectionUtils.isEmpty(headers)) {
            Set<String> set = headers.keySet();
            for (String key : set) {
                if (ObjectUtil.isNotNull(headers.get(key))) {
                    builder.addHeader(key, String.valueOf(headers.get(key)));
                }
            }
        }

        Request request = builder.build();
        long begin = System.currentTimeMillis();
        try (Response response = okHttpClient.newCall(request).execute();) {
            if (response.isSuccessful()) {
                return response.body().string();
            } else {
                log.error("response >>>", response);
                log.error("第三方接口:{},头部:{},参数:{},状态码:{}:{}", url, JSON.toJSONString(headers), json, response.code(),
                    response.body().string());
                throw new IOException("第三方接口返回http状态码为" + response.code());
            }
        } catch (Exception e) {
            log.error("okhttp3 post exception：{}", e.getMessage(), e);
            throw new RuntimeException(e.getMessage());
        } finally {
            log.info("第三方接口:{},头部:{},参数:{},,耗时{}ms", url, JSON.toJSONString(headers), json,
                System.currentTimeMillis() - begin);
        }
    }

    public static JSONObject postFiles(String url, List<File> files, String fileName, String mediaType,
        JSONObject params) throws IOException {

        MultipartBody.Builder mBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM); // 设置请求体类型为表单类型

        StringBuilder sb = new StringBuilder();
        for (File file : files) {
            mBuilder.addFormDataPart(fileName, file.getName(), RequestBody.create(file, MediaType.parse(mediaType)));
            sb.append(file.getName()).append(",");
        }

        if (ObjectUtil.isNotNull(params)) {
            params.forEach((key, object) -> {
                System.out.println("key:" + key);
                System.out.println("object:" + object);
                mBuilder.addFormDataPart(key, String.valueOf(object));
            });
        }

        RequestBody requestBody = mBuilder.build();

        Request request = new Request.Builder().url(url).post(requestBody).build();
        long begin = System.currentTimeMillis();
        try (Response response = okHttpClient.newCall(request).execute();) {
            if (response.isSuccessful()) {
                String result = response.body().string();
                log.info("result = {}", result);
                JSONObject data = JSONObject.parse(result);
                return data;
            } else {
                log.error("第三方接口:{},参数:{},状态码:{}", url, sb.toString() + ":" + params, response.code());
                throw new IOException("第三方接口返回http状态码为" + response.code());
            }
        } catch (Exception e) {
            log.error("okhttp3 post exception：{}", e.getMessage(), e);
            throw new RuntimeException(e.getMessage());
        } finally {
            log.info("okhttp3 post {},耗时{}ms", url, System.currentTimeMillis() - begin);
        }
    }

    public static String postFileWithHeader(String url, File file, String mediaType, JSONObject params,
        JSONObject headers) throws IOException {

        MultipartBody.Builder mBuilder = new MultipartBody.Builder();
        mBuilder.setType(MultipartBody.FORM);
        mBuilder.addFormDataPart("file", file.getName(), RequestBody.create(file, MediaType.parse(mediaType)));

        if (ObjectUtil.isNotNull(params)) {
            params.forEach((key, object) -> {
                mBuilder.addFormDataPart(key, String.valueOf(object));
            });
        }
        MultipartBody multipartBody = mBuilder.build();

        Request.Builder builder = new Request.Builder();
        if (!CollectionUtils.isEmpty(headers)) {
            headers.forEach((key, object) -> {
                builder.addHeader(key, String.valueOf(headers.get(key)));
            });
        }

        Request request = builder.url(url).post(multipartBody).build();
        long begin = System.currentTimeMillis();
        try (Response response = okHttpClient.newCall(request).execute();) {
            if (response.isSuccessful()) {
                String result = response.body().string();
                log.info("result = {}", result);
                // JSONObject data = JSONObject.parse(result);
                return result;
            } else {
                log.error("第三方接口:{},参数:{},状态码:{}", url, file.getName() + ":" + params, response.code());
                throw new IOException("第三方接口返回http状态码为" + response.code());
            }
        } catch (Exception e) {
            log.error("okhttp3 post exception：{}", e.getMessage(), e);
            throw new RuntimeException(e.getMessage());
        } finally {
            log.info("okhttp3 post {},参数:{},耗时{}ms", url, file.getName() + ":" + params,
                System.currentTimeMillis() - begin);
        }
    }

    /**
     * 特定接口，aimotion用
     * 
     * @param url
     * @param files
     * @param headers
     * @param mediaType
     * @return
     * @throws IOException
     */
    public static JSONObject postFile(String url, File file, String fileName, String mediaType, JSONObject params)
        throws IOException {

        MultipartBody.Builder mBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM)
            .addFormDataPart(fileName, file.getName(), RequestBody.create(file, MediaType.parse(mediaType)));

        if (ObjectUtil.isNotNull(params)) {
            params.forEach((key, object) -> {
                mBuilder.addFormDataPart(key, String.valueOf(object));
            });
        }

        RequestBody requestBody = mBuilder.build();

        Request request = new Request.Builder().url(url).post(requestBody).build();
        long begin = System.currentTimeMillis();
        try (Response response = okHttpClient.newCall(request).execute();) {
            if (response.isSuccessful()) {
                String result = response.body().string();
                log.info("result = {}", result);
                JSONObject data = JSONObject.parse(result);
                return data;
            } else {
                log.error("第三方接口:{},参数:{},状态码:{}", url, file.getName() + ":" + params, response.code());
                throw new IOException("第三方接口返回http状态码为" + response.code());
            }
        } catch (Exception e) {
            log.error("okhttp3 post exception：{}", e.getMessage(), e);
            throw new RuntimeException(e.getMessage());
        } finally {
            log.info("okhttp3 post {},参数:{},耗时{}ms", url, fileName + ":" + file.getName() + ":" + params,
                System.currentTimeMillis() - begin);
        }
    }

    /**
     * 特定接口，aimotion用
     * 
     * @param url
     * @param files
     * @param headers
     * @param mediaType
     * @return
     * @throws IOException
     */
    public static String postFileForAudioEnhance(File audioFile) throws IOException {

        String url = "https://cloud.ifootoo.com/wisper/audio2Text";
        // String url = "http://localhost:8899/video";
        // 使用MultipartBody上传多个文件，Builder构建着

        MultipartBody.Builder mBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM)
            .addFormDataPart("audio", audioFile.getName(), RequestBody.create(audioFile, MediaType.parse("audio/*")));

        RequestBody requestBody = mBuilder.build();

        Request request = new Request.Builder().url(url).post(requestBody).build();
        long begin = System.currentTimeMillis();
        try (Response response = okHttpClient.newCall(request).execute();) {
            if (response.isSuccessful()) {
                String result = response.body().string();
                JSONObject data = JSONObject.parse(result);
                return data.getString("data");
            } else {
                log.error("第三方接口:{},参数:{},状态码:{}", url, audioFile.getName(), response.code());
                throw new IOException("第三方接口返回http状态码为" + response.code());
            }
        } catch (Exception e) {
            log.error("okhttp3 post exception：{}", e.getMessage(), e);
            throw new RuntimeException(e.getMessage());
        } finally {
            log.error("okhttp3 post {},耗时{}ms", url, System.currentTimeMillis() - begin);
        }
    }

    /**
     * 特定接口，aimotion用
     * 
     * @param url
     * @param files
     * @param headers
     * @param mediaType
     * @return
     * @throws IOException
     */
    public static String postFileForImageAimotion(String fileName, File driven_audio, File source_image,
        File refEyeblinkFile, File refPoseFile, JSONObject param) throws IOException {

        String url = "http://localhost:8899/video";
        // 使用MultipartBody上传多个文件，Builder构建着

        MultipartBody.Builder mBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM)
            .addFormDataPart("driven_audio", driven_audio.getName(),
                RequestBody.create(driven_audio, MediaType.parse("audio/*")))
            .addFormDataPart("source_image", source_image.getName(),
                RequestBody.create(source_image, MediaType.parse("image/*")))
            // .addFormDataPart("param", param.toJSONString())
            // .addFormDataPart("param", "param", RequestBody.create(param.toJSONString(), JSON_MT))
            .addFormDataPart("enhancer",
                StrUtil.isNotBlank(param.getString("enhancer")) ? param.getString("enhancer") : "gfpgan")
            .addFormDataPart("preprocess",
                StrUtil.isNotBlank(param.getString("preprocess")) ? param.getString("preprocess") : "crop")
            .addFormDataPart("face3dvis",
                StrUtil.isNotBlank(param.getString("face3dvis")) ? param.getString("face3dvis") : "")
            .addFormDataPart("input_yaw",
                StrUtil.isNotBlank(param.getString("input_yaw")) ? param.getString("input_yaw") : "")
            .addFormDataPart("input_roll",
                StrUtil.isNotBlank(param.getString("input_roll")) ? param.getString("input_roll") : "-5,0,5")
            .addFormDataPart("input_pitch",
                StrUtil.isNotBlank(param.getString("input_pitch")) ? param.getString("input_pitch") : "");

        if (ObjUtil.isNotNull(refEyeblinkFile)) {
            mBuilder = mBuilder.addFormDataPart("ref_eyeblink", refEyeblinkFile.getName(),
                RequestBody.create(refEyeblinkFile, MediaType.parse("application/mp4")));
        }
        if (ObjUtil.isNotNull(refPoseFile)) {
            mBuilder = mBuilder.addFormDataPart("ref_pose", refPoseFile.getName(),
                RequestBody.create(refPoseFile, MediaType.parse("application/mp4")));
        }
        if (ObjUtil.isNotNull(refPoseFile)) {
            mBuilder = mBuilder.addFormDataPart("ref_pose", refPoseFile.getName(),
                RequestBody.create(refPoseFile, MediaType.parse("application/mp4")));
        }

        RequestBody requestBody = mBuilder.build();

        Request request = new Request.Builder().url(url).post(requestBody).build();
        long begin = System.currentTimeMillis();
        try (Response response = okHttpClient.newCall(request).execute();) {
            if (response.isSuccessful()) {
                InputStream inputStream = response.body().byteStream();
                FileOutputStream fileOutputStream = new FileOutputStream(AIMOTION_MP4 + fileName);

                // We can use a buffer to read and write the data in chunks
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    fileOutputStream.write(buffer, 0, bytesRead);
                }
                fileOutputStream.close();
                return fileName;
            } else {
                log.error("response >>>", response);
                log.error("第三方接口:{},状态码:{}:{}", url, response.code(), response.body().string());
                throw new IOException("第三方接口返回http状态码为" + response.code());
            }
        } catch (Exception e) {
            log.error("okhttp3 post exception：{}", e.getMessage(), e);
            throw new RuntimeException(e.getMessage());
        } finally {
            log.info("第三方接口:{},耗时{}ms", url, System.currentTimeMillis() - begin);
        }
    }

    public static String postGetFile(String url, JSONObject params, String fileName) throws IOException {

        RequestBody body = RequestBody.create(params.toJSONString(), JSON_MT);
        Request.Builder builder = new Request.Builder().url(url).post(body);

        Request request = builder.build();
        long begin = System.currentTimeMillis();
        try (Response response = okHttpClient.newCall(request).execute();) {
            if (response.isSuccessful()) {
                InputStream inputStream = response.body().byteStream();
                File path = new File("/tmp/client/translated_files");
                if (!path.exists()) {
                    path.mkdirs();
                }
                FileOutputStream fileOutputStream = new FileOutputStream("/tmp/client/" + fileName);

                // We can use a buffer to read and write the data in chunks
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    fileOutputStream.write(buffer, 0, bytesRead);
                }
                fileOutputStream.close();
                return fileName;
            } else {
                log.error("response >>>", response);
                log.error("第三方接口:{},状态码:{}:{}", url, response.code(), response.body().string());
                throw new IOException("第三方接口返回http状态码为" + response.code());
            }
        } catch (Exception e) {
            log.error("okhttp3 post exception：{}", e.getMessage(), e);
            throw new RuntimeException(e.getMessage());
        } finally {
            log.info("第三方接口:{},耗时{}ms", url, System.currentTimeMillis() - begin);
        }
    }

    /**
     * 特定接口，aimotion用
     * 
     * @param url
     * @param files
     * @param headers
     * @param mediaType
     * @return
     * @throws IOException
     */
    public static String postFileForVideoAimotion(String fileName, File driven_audio, File source_video)
        throws IOException {

        String url = "http://localhost:8899/video";
        // 使用MultipartBody上传多个文件，Builder构建着

        MultipartBody.Builder mBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM)
            .addFormDataPart("driven_audio", driven_audio.getName(),
                RequestBody.create(driven_audio, MediaType.parse("audio/*")))
            .addFormDataPart("source_video", source_video.getName(),
                RequestBody.create(source_video, MediaType.parse("video/*")));

        RequestBody requestBody = mBuilder.build();

        Request request = new Request.Builder().url(url).post(requestBody).build();
        long begin = System.currentTimeMillis();
        try (Response response = okHttpClient.newCall(request).execute();) {
            if (response.isSuccessful()) {
                InputStream inputStream = response.body().byteStream();
                FileOutputStream fileOutputStream = new FileOutputStream(AIMOTION_MP4 + fileName);

                // We can use a buffer to read and write the data in chunks
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    fileOutputStream.write(buffer, 0, bytesRead);
                }
                fileOutputStream.close();
                return fileName;
            } else {
                log.error("response >>>", response);
                log.error("第三方接口:{},状态码:{}:{}", url, response.code(), response.body().string());
                throw new IOException("第三方接口返回http状态码为" + response.code());
            }
        } catch (Exception e) {
            log.error("okhttp3 post exception：{}", e.getMessage(), e);
            throw new RuntimeException(e.getMessage());
        } finally {
            log.info("第三方接口:{},耗时{}ms", url, System.currentTimeMillis() - begin);
        }
    }

    // public static String doGet(String url){
    // //创建一个Request
    // final Request request = new Request.Builder()
    // .url(url)
    // .build();
    // return execute(request);
    // }
    // public static String doPost(String url,String reqbody,Map<String,Object> map){
    //
    // FormEncodingBuilder builder=addParamToBuilder(reqbody, map);
    // RequestBody body = builder.build();
    // Request request = new Request.Builder()
    // .url(url)
    // .post(body)
    // .build();
    // return execute(request);
    // }
    //
    // public static String doPut(String url,String reqbody,Map<String,Object> map){
    // FormEncodingBuilder builder=addParamToBuilder(reqbody, map);
    // RequestBody body = builder.build();
    // Request request = new Request.Builder()
    // .url(url)
    // .put(body)
    // .build();
    // return execute(request);
    // }
    // public static String doDelete(String url,String reqbody,Map<String,Object> map){
    // FormEncodingBuilder builder=addParamToBuilder(reqbody, map);
    // RequestBody body = builder.build();
    // Request request = new Request.Builder()
    // .url(url)
    // .delete(body)
    // .build();
    // return execute(request);
    // }
    // public static FormEncodingBuilder addParamToBuilder(String reqbody,Map<String,Object> map){
    // FormEncodingBuilder builder=new FormEncodingBuilder();
    // if(!StringUtils.isEmpty(reqbody)){
    // if(reqbody.startsWith("?")){
    // reqbody=reqbody.substring(1);
    // }
    // String[] params=reqbody.split("&");
    // for(int i=0;i<params.length;i++){
    // if(params[i].equals("")){
    // continue;
    // }
    // String [] kv=params[i].split("=");
    // builder.add(kv[0], kv[1]);
    // }
    // }
    // if(map!=null){
    // Iterator<Entry<String,Object>> ite= map.entrySet().iterator();
    // for(;ite.hasNext();){
    // Entry<String,Object> kv=ite.next();
    // builder.add(kv.getKey(), kv.getValue().toString());
    // }
    // }
    // return builder;
    // }
    //
    // public static String execute(Request request){
    // try {
    // OkHttpClient client = new OkHttpClient();
    // Response response = client.newCall(request).execute();
    // if (response.isSuccessful()) {
    // return response.body().string();
    // }
    // } catch (IOException e) {
    // e.printStackTrace();
    // }
    // return "{\"error\":\"fail\"}";
    // }

}